package com.store.orm.mysql.handler;

import com.store.orm.mysql.MySQLUtil;
import com.store.orm.util.FieldUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 宫静雨
 * @version 1.0
 */
public class ValueRSHandler implements ResultSetHandler {
    private MySQLUtil UTIL;
    private static final Logger logger = LoggerFactory.getLogger(ValueRSHandler.class);

    public ValueRSHandler(MySQLUtil UTIL) {
        this.UTIL = UTIL;
    }

    @Override
    public Map<String, Object> handler(ResultSet resultSet) {
        try {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            Map<String, Object> map = new LinkedHashMap<>();
            if (resultSet.next()) {
                for (int i = 0; i < columnCount; i++) {
                    String key = metaData.getColumnLabel(i + 1);
                    Object v = resultSet.getObject(i + 1);
                    if (UTIL.isCamelCase()) {
                        key = FieldUtil.mysqlToPojo(key);
                    }
                    map.put(key, v);
                }
            }
            return map;
        } catch (SQLException e) {
            logger.error("处理 ResultSet 时发生错误{}", e.getMessage());
            throw new RuntimeException();
        }
    }

    @Override
    public <T> T handler(ResultSet resultSet, Class<T> cls) {
        try {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            T res = cls.newInstance();
            if (resultSet.next()) {
                for (int i = 0; i < columnCount; i++) {
                    String key = metaData.getColumnLabel(i + 1);
                    Object v = resultSet.getObject(i + 1);
                    if (UTIL.isCamelCase()) {
                        key = FieldUtil.mysqlToPojo(key);
                    }
                    Field field = cls.getDeclaredField(key);
                    field.setAccessible(true);
                    field.set(res, v);
                }
            }
            return res;
        } catch (Exception e) {
            logger.error("处理 ResultSet 时发生错误{}", e.getMessage());
            throw new RuntimeException();
        }
    }
}
